//切换tab底栏时复用3次的输入框
//分别三次的格式是：
//1.当天：20201010(8位)
//2.近期：202010(6位)
//3.当年：2020(4位)
//以上，需要设置maxlength长度和每个路由对于不同的placeholder

<template>
  <div class="search-wrapper">
    <!-- @input="searchData($event)" 一边输入一边搜索 -->
    <input
      type="text"
      :placeholder="placeholder"
      :maxlength="maxlength"
      :value="inputValue"
      @input="searchData($event)"
    />
  </div>
</template>

<script>
import { ref, computed, watch } from "vue";
import { useStore } from "vuex";
import getData from "../../services/index";
import { formatUserDate, getNowDate } from "../../libs/utils";

export default {
  name: "SearchInput",
  props: {
    placeholder: String,
    maxlength: Number,
  },
  setup(props) {
    //仅仅在这个子组件里使用value数据
    //ref声明的是一个单独的data
    const inputValue = ref(""),
      store = useStore(),
      state = store.state;

    //定义事件处理函数
    const searchData = (e) => {
      inputValue.value = e.target.value;
      const field = computed(() => state.field).value;

      //搜索
      if (inputValue.value.length === props.maxlength) {
        getData(store, field, formatUserDate(inputValue.value));
      } else if (inputValue.value.length === 0) {
        //输出框清零时回到当天信息
        getData(store, field, getNowDate(field));
      }
    };

    watch(
      () => {
        return state.field;
      },
      () => {
        inputValue.value = "";
      }
    );

    return {
      inputValue,
      //事件处理函数也一并返回出去供视图使用：@input="searchData($event)"
      searchData,
    };
  },
};
</script>

<style lang="scss" scoped>
.search-wrapper {
  position: fixed;
  top: 0.44rem;
  left: 0;
  z-index: 1;
  width: 100%;
  height: 0.38rem;
  padding: 0.03rem 0.1rem;
  border-bottom: 1px solid #ddd;
  box-sizing: border-box;
  background-color: #fff;

  input {
    width: 100%;
    height: 100%;
    font-size: 0.14rem;
    border: 1px solid #ddd;
    text-indent: 0.1rem;
    border-radius: 0.03rem;

    &.focus {
      border-color: #ed4040;
      box-shadow: 0 0 0.02rem #ed4040;
      transition: all 0.3s;
    }
  }
}
</style>